﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "login/logindlg.h"
#include "CommUtil/common.h"
#include<QMessageBox>
#include <QDebug>
#include<Qdir>
#include"mydocktitlebar.h"
#include"mytabbar.h"

extern MainWindow* g_pMainwindow;
extern CLoginDlg*  g_pLoginDlg;
extern CTPInterface* g_CTPInterface;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->layout()->setMargin(0);
    this->layout()->setSpacing(0);
    setDockNestingEnabled(true);

    ComFunc::LogFileInit();

    QWidget* p = takeCentralWidget();
    if(p)
        delete p;

    statusBar()->setFixedHeight(10);

    m_pOrderSetterDlg = new OrderSetterDlg();
    m_MainPopDialog = new MainPopDialog;
    m_SettlementInfoDialog   = new SettlementInfoDialog;//客户结算单确认Dialog

    marketselfwidget = new MarketSelfWidget;
    ui->dockWidget1->setWidget(marketselfwidget);
    ui->dockWidget1->setWindowTitle(QStringLiteral("自选行情"));

    controlwidget = new ControlWidget;
    ui->dockWidget2->setWidget( controlwidget);
    ui->dockWidget2->setWindowTitle(QStringLiteral("下单面板"));

    maincombineentrustwidget = new MainCombineEntrustWidget;
    ui->dockWidget3->setWidget(maincombineentrustwidget);
    ui->dockWidget3->setWindowTitle(QStringLiteral("未成交单"));

    mainholdwidget = new MainHoldWidget(this);
    ui->dockWidget4->setWidget(mainholdwidget);
    ui->dockWidget4->setWindowTitle(QStringLiteral("持仓一览"));

    mainbalancewidget = new MainBalanceWidget(this);//资金
    ui->dockWidget5->setWidget(mainbalancewidget);
    ui->dockWidget5->setWindowTitle(QStringLiteral("资金一览"));
    tabifyDockWidget(ui->dockWidget4, ui->dockWidget5);

    mainbusinessqueryhiswidget = new MainBusinessQueryHisWidget;//成交查询
    ui->dockWidget6->setWidget(mainbusinessqueryhiswidget);
    ui->dockWidget6->setWindowTitle(QStringLiteral("成交查询"));
    tabifyDockWidget(ui->dockWidget3, ui->dockWidget6);

    maincontractwidget = new MainContractWidget;//合约查询
    ui->dockWidget7->setWidget(maincontractwidget);
    ui->dockWidget7->setWindowTitle(QStringLiteral("合约查询"));
    tabifyDockWidget(ui->dockWidget4, ui->dockWidget7);

    setTabPosition(Qt::AllDockWidgetAreas,QTabWidget::North);

    //ui->dockWidget1->setTitleBarWidget(new MyDockTitleBar());
    //ui->dockWidget2->setTitleBarWidget(new MyDockTitleBar());
    ui->dockWidget3->setTitleBarWidget(new MyDockTitleBar());
    ui->dockWidget4->setTitleBarWidget(new MyDockTitleBar());
    ui->dockWidget5->setTitleBarWidget(new MyDockTitleBar());
    ui->dockWidget6->setTitleBarWidget(new MyDockTitleBar());
    ui->dockWidget7->setTitleBarWidget(new MyDockTitleBar());
    connect(ui->dockWidget1,SIGNAL(dockLocationChanged(Qt::DockWidgetArea)),this,SLOT(SlotdockLocationChanged1(Qt::DockWidgetArea)));
    connect(ui->dockWidget2,SIGNAL(dockLocationChanged(Qt::DockWidgetArea)),this,SLOT(SlotdockLocationChanged1(Qt::DockWidgetArea)));
    connect(ui->dockWidget3,SIGNAL(dockLocationChanged(Qt::DockWidgetArea)),this,SLOT(SlotdockLocationChanged1(Qt::DockWidgetArea)));
    connect(ui->dockWidget4,SIGNAL(dockLocationChanged(Qt::DockWidgetArea)),this,SLOT(SlotdockLocationChanged1(Qt::DockWidgetArea)));
    connect(ui->dockWidget5,SIGNAL(dockLocationChanged(Qt::DockWidgetArea)),this,SLOT(SlotdockLocationChanged1(Qt::DockWidgetArea)));
    connect(ui->dockWidget6,SIGNAL(dockLocationChanged(Qt::DockWidgetArea)),this,SLOT(SlotdockLocationChanged1(Qt::DockWidgetArea)));
    connect(ui->dockWidget7,SIGNAL(dockLocationChanged(Qt::DockWidgetArea)),this,SLOT(SlotdockLocationChanged1(Qt::DockWidgetArea)));

    connect(marketselfwidget->m_tableView, SIGNAL(clicked(const QModelIndex &)), controlwidget, SLOT(SelectContract(const QModelIndex &)));
    connect(marketselfwidget->m_tableView, SIGNAL(SigkeyPressEvent(QKeyEvent*)), this, SLOT(SlotkeyPressEvent(QKeyEvent*)));
	connect(marketselfwidget,SIGNAL(SigControlWgtInfo(double,double,double,double)),controlwidget,SLOT(SlotUpdateShowInfo(double,double,double,double)));
    connect(mainbalancewidget, SIGNAL(SigkeyPressEvent(QKeyEvent*)), this, SLOT(SlotkeyPressEvent(QKeyEvent*)));
    connect(mainholdwidget, SIGNAL(SigkeyPressEvent(QKeyEvent*)), this, SLOT(SlotkeyPressEvent(QKeyEvent*)));
    connect(maincombineentrustwidget, SIGNAL(SigkeyPressEvent(QKeyEvent*)), this, SLOT(SlotkeyPressEvent(QKeyEvent*)));
    connect(mainbusinessqueryhiswidget, SIGNAL(SigkeyPressEvent(QKeyEvent*)), this, SLOT(SlotkeyPressEvent(QKeyEvent*)));
    connect(maincontractwidget, SIGNAL(SigkeyPressEvent(QKeyEvent*)), this, SLOT(SlotkeyPressEvent(QKeyEvent*)));

    connect(this->controlwidget,SIGNAL(SigOrderInsert(const char*,const char*,char,char,char,int,double)),this,SLOT(OrderInsert(const char*,const char*,char,char,char,int,double)));
    connect(this->mainholdwidget,SIGNAL(SigClosePositon(QString,QString,char,char,char,int,int)),this,SLOT(SlotClosePositon(QString,QString,char,char,char,int,int)));

    connect(m_pOrderSetterDlg,SIGNAL(SigSetHandsTimes(int)),controlwidget,SLOT(SlotSetHandsTimes(int)));
    connect(m_pOrderSetterDlg,SIGNAL(SigChangeOrder(int)),maincombineentrustwidget,SLOT(SlotChangeOrder(int)));
    connect(m_pOrderSetterDlg,SIGNAL(SigFastOrder(FastInfo*)),this,SLOT(SlotOrderInsert(FastInfo*)));

    connect(maincombineentrustwidget,SIGNAL(SigCancelOrder(TThostFtdcExchangeIDType&,TThostFtdcOrderSysIDType&,int)),this,SLOT(SlotCancelOrder(TThostFtdcExchangeIDType&,TThostFtdcOrderSysIDType&,int)));
    connect(m_pOrderSetterDlg,SIGNAL(SigHideCancelOrderButtonToggled(bool)),maincombineentrustwidget,SLOT(SlotHideCancelOrderButtonToggled(bool)));

    connect(controlwidget,SIGNAL(SigGetOpenRatio(char,QString,QString,double)),this,SLOT(SlotGetOpenRatio(char,QString,QString,double)));
    connect(this,SIGNAL(SigRaiseOrderDockWidget()),ui->dockWidget3,SLOT(raise()));
    connect(this,SIGNAL(SigShowSettlementInfoDialog()),this,SLOT(SlotShowSettlementInfoDialog()));


    statusBar();
    createActions();
    createMenus();
    setWindowTitle(QStringLiteral("速赢期货交易客户端2.0"));
    this->setFocusPolicy(Qt::StrongFocus);
}

void MainWindow::SlotdockLocationChanged(int index){
    QDockWidget *  tmp = NULL;
    QList<QDockWidget*> lst;
    switch(index){
    case 1:tmp = ui->dockWidget1;        break;
    case 2:tmp = ui->dockWidget2;        break;
    case 3:tmp = ui->dockWidget3;        break;
    case 4:tmp = ui->dockWidget4;        break;
    case 5:tmp = ui->dockWidget5;        break;
    case 6:tmp = ui->dockWidget6;        break;
    case 7:tmp = ui->dockWidget7;        break;
    }
    lst = tabifiedDockWidgets(tmp);
	if(lst.size() == 0){
        delete tmp->titleBarWidget();
	}else{
        tmp->setTitleBarWidget(new MyDockTitleBar());
	}
}
void MainWindow::SlotdockLocationChanged1(Qt::DockWidgetArea){
    //SlotdockLocationChanged(1);
    QList<QDockWidget*> lst = tabifiedDockWidgets(ui->dockWidget1);
    if(lst.size() == 0){
        delete ui->dockWidget1->titleBarWidget();
    }else{
        for(int i = 0; i < lst.size(); i++){
            lst.at(i)->setTitleBarWidget(new MyDockTitleBar());
        }
    }
    lst = tabifiedDockWidgets(ui->dockWidget2);
    if(lst.size() == 0){
        delete ui->dockWidget2->titleBarWidget();
    }else{
        for(int i = 0; i < lst.size(); i++){
            lst.at(i)->setTitleBarWidget(new MyDockTitleBar());
        }
    }
    lst = tabifiedDockWidgets(ui->dockWidget3);
    if(lst.size() == 0){
        delete ui->dockWidget3->titleBarWidget();
    }else{
        for(int i = 0; i < lst.size(); i++){
            lst.at(i)->setTitleBarWidget(new MyDockTitleBar());
        }
    }
    lst = tabifiedDockWidgets(ui->dockWidget4);
    if(lst.size() == 0){
        delete ui->dockWidget4->titleBarWidget();
    }else{
        for(int i = 0; i < lst.size(); i++){
            lst.at(i)->setTitleBarWidget(new MyDockTitleBar());
        }
    }
    lst = tabifiedDockWidgets(ui->dockWidget5);
    if(lst.size() == 0){
        delete ui->dockWidget5->titleBarWidget();
    }else{
        for(int i = 0; i < lst.size(); i++){
            lst.at(i)->setTitleBarWidget(new MyDockTitleBar());
        }
    }
    lst = tabifiedDockWidgets(ui->dockWidget6);
    if(lst.size() == 0){
        delete ui->dockWidget6->titleBarWidget();
    }else{
        for(int i = 0; i < lst.size(); i++){
            lst.at(i)->setTitleBarWidget(new MyDockTitleBar());
        }
    }
    lst = tabifiedDockWidgets(ui->dockWidget7);
    if(lst.size() == 0){
        delete ui->dockWidget7->titleBarWidget();
    }else{
        for(int i = 0; i < lst.size(); i++){
            lst.at(i)->setTitleBarWidget(new MyDockTitleBar());
        }
    }

}
void MainWindow::SlotdockLocationChanged2(Qt::DockWidgetArea){
    SlotdockLocationChanged(2);
}
void MainWindow::SlotdockLocationChanged3(Qt::DockWidgetArea){
    SlotdockLocationChanged(3);
}
void MainWindow::SlotdockLocationChanged4(Qt::DockWidgetArea){
    SlotdockLocationChanged(4);
}
void MainWindow::SlotdockLocationChanged5(Qt::DockWidgetArea){
    SlotdockLocationChanged(5);
}
void MainWindow::SlotdockLocationChanged6(Qt::DockWidgetArea){
    SlotdockLocationChanged(6);
}
void MainWindow::SlotdockLocationChanged7(Qt::DockWidgetArea){
    SlotdockLocationChanged(7);
}

MainWindow::~MainWindow(){
    ComFunc::LogFileRelease();
}
//创建Actions
void MainWindow::createActions()
{
    newAct=new QAction(QStringLiteral("&退出"),this);
    newAct->setShortcut(QKeySequence("X"));//设置快捷键
    newAct->setStatusTip(QStringLiteral("退出"));//设置状态栏提示

    newAct1=new QAction(QStringLiteral("&自选行情设置"),this);
    newAct1->setStatusTip(QStringLiteral("自选行情设置"));//设置状态栏提示

    m_pOrderSetterAction = new QAction(QStringLiteral("&报单设置"),this);
    m_pOrderSetterAction->setStatusTip(QStringLiteral("报单设置"));

    aboutAct1=new QAction(QStringLiteral("&打开帮助文档"),this);
    aboutAct1->setStatusTip(QStringLiteral("打开帮助文档"));
}
void MainWindow::createMenus(){
    //文件菜单
    fileMenu = menuBar()->addMenu(QStringLiteral("&文件(F)"));
    fileMenu->addAction(newAct);//退出
    editMenu = menuBar()->addMenu(QStringLiteral("&系统(S)"));
    editMenu->addAction(newAct1);
    editMenu->addAction(m_pOrderSetterAction);
    //帮助菜单
    helpMenu = menuBar()->addMenu(QStringLiteral("&帮助(H)"));
    helpMenu->addAction(aboutAct1);

    connect(newAct, SIGNAL(triggered()), this, SLOT(exit()));
    connect(newAct1, SIGNAL(triggered()), this, SLOT(MainPopDlgShow()));
    connect(m_pOrderSetterAction,SIGNAL(triggered()),this,SLOT(OrderSetterDlgShow()));
}
void MainWindow::SlotkeyPressEvent ( QKeyEvent * k ){
    this->keyPressEvent(k);
}
void MainWindow::SlotGetOpenRatio(char bs,QString ordertype,QString futucode,double price){
    //获取开仓保证金比例
    double ratio = maincontractwidget->GetOpenRatio(bs,ordertype,futucode);
    double dEnableBalance = mainbalancewidget->GetEnableBalance();
    int    iAmountPerHand = maincontractwidget->GetAmountPerHand(futucode);

    if(ratio > 0 && iAmountPerHand >0){
        int iCnt = floor(dEnableBalance /(price *iAmountPerHand * ratio ));
        controlwidget->SetEnableAmount(iCnt);
    }
}
///撤单
void MainWindow::SlotCancelOrder(TThostFtdcExchangeIDType& ExchangeID, TThostFtdcOrderSysIDType& entrust_no,int CancelType){
    if(CancelType == 2){///鼠标双击撤单
        if(!m_pOrderSetterDlg->GetCancelOrderDoubleClickedFlg()){
            return;
        }
    }
    if( m_pOrderSetterDlg->GetCancelOrderConfirmFlg() ){///撤单前确认
        QString msg = QStringLiteral("是否撤销委托单 ")+ QString(entrust_no) + QStringLiteral(" ?");
        int ret =  QMessageBox::question(this,QString("Question"),msg);
        if (ret == QMessageBox::No)
            return;
    }
    g_CTPInterface->DeleteOrder(entrust_no,ExchangeID);
}
/// 改单
void MainWindow::SlotChangeOrder(){

}

//平所持持仓
void MainWindow::SlotClosePositon(QString exch_type,QString contract_code, char c_bs, char c_direction, char c_hedge,int real_enable_amount,int enable_amount){
    if(real_enable_amount > 0 && m_pOrderSetterDlg->GetPingJinCangFlg()){//警告  禁止平今仓
        QMessageBox::critical(this,QString("ERROR"),QStringLiteral("禁止平今仓!"));
        return;
    }
	if (enable_amount == 0){
		QMessageBox::critical(this,QString("ERROR"),QStringLiteral("可用持仓不足!"));
		return;
	}
    //获取报单价格类型  对价 市价 超价
    double en_entrust_price;
    QString entrust_prop  = "F0";
    QString priceType = m_pOrderSetterDlg->GetClosePositionPriceType();
    if(priceType == QStringLiteral("对手价")){
        if(c_bs == THOST_FTDC_D_Buy){
            en_entrust_price = marketselfwidget->GetSell1Price(contract_code);
        }else{
            en_entrust_price = marketselfwidget->GetBuy1Price(contract_code);
        }
    }else if(priceType == QStringLiteral("市场价")){
        entrust_prop= "F1";//市价单
        en_entrust_price = 0.0;
    }else if(priceType == QStringLiteral("超价")){

    }
    //获取报单平仓手数  全平  默认手数平仓
    int l_entrust_amount;
    QString cntType = m_pOrderSetterDlg->GetClosePositionCntType();
    if(cntType == QStringLiteral("默认手数平仓")){
        l_entrust_amount = m_pOrderSetterDlg->GetDefaultOrderCnt();
    }else if(cntType == QStringLiteral("持仓全平")){
        l_entrust_amount = enable_amount;
    }
    if(m_pOrderSetterDlg->GetClosePositionFlg()){//平所持持仓 是否进行确认
        QString msg = QStringLiteral("是否使用 ")+priceType+QString::number(en_entrust_price) +QStringLiteral(" 对 ") +
                QString::number(l_entrust_amount) + QStringLiteral(" 手 ")+  contract_code + QStringLiteral(" 进行平仓 ?");
        int ret =  QMessageBox::question(this,QString("Question"),msg);
        if (ret == QMessageBox::Yes){
            g_CTPInterface->OrderInsert(exch_type.toStdString().c_str(),contract_code.toStdString().c_str(),
                                               c_bs,c_direction,c_hedge,l_entrust_amount,en_entrust_price,entrust_prop.toStdString().c_str());
        }
    }
}

void MainWindow::OrderInsert(const char* exch_type, const char* contract_code, char c_bs, char c_direction, char c_hedge, int l_entrust_amount, double en_entrust_price){
    if(c_direction == '2' || c_direction == '4'){//如果是平仓的情况下 去查询今日可用持仓
        int amount = 0;
        if(c_bs == '1'){//买平
            amount = mainholdwidget->GetRealEnableAmount(QString(contract_code),'2');
        }else if(c_bs == '2'){//卖平
            amount = mainholdwidget->GetRealEnableAmount(QString(contract_code),'1');
        }
        if(amount > 0 && m_pOrderSetterDlg->GetPingJinCangFlg()){//警告  禁止平今仓
            QMessageBox::critical(this,QString("ERROR"),QStringLiteral("禁止平今仓!"));
            return;
        }
    }
    g_CTPInterface->OrderInsert(exch_type,contract_code,c_bs,c_direction,c_hedge,l_entrust_amount,en_entrust_price,"F0");
}
/*******************************************
 * bs          1:买入   2:卖出
 * c_hedge     0:投机   1:套保   ///组合投机套保标志 '0'	投机     '1'	套保
 * c_direction 1:开仓   2:平仓   4:平今仓
 * overprice   超价
 * makesureFlg      发出报单是否确认
 * movetopriceFlg   谈单后光标是否移动到价格
 * ****************************************/
void MainWindow::SlotOrderInsert(FastInfo* pFastInfo){
    QString msg = QStringLiteral("是否以");
    ///合约代码
    QString contractName = controlwidget->GetContractCode();
    if(contractName == ""){
        QMessageBox::critical(this,QString("ERROR"),QStringLiteral("请输入有效的合约代码！"));
        return;
    }
    int l_entrust_amount = controlwidget->GetTotalHands();///手数
    double overprice     = maincontractwidget->GetPriceStep(contractName);///最小变动价位
    QString futuexchtype = controlwidget->GetFutuExchType();///交易所
    char c_direction = '1';///开仓
    double en_entrust_price = 0.0;///委托价格
    char bs = THOST_FTDC_D_Buy; ///买卖
    char c_hedge = '1';
    QString entrust_prop  = "F0";

    switch(pFastInfo->PriceType){
    case 0://最新价
        en_entrust_price = marketselfwidget->GetLastPrice(contractName) + pFastInfo->OverPrice* overprice;
        msg = msg + QStringLiteral(" 最新价 ")+ QString::number(en_entrust_price);
        break;
    case 1://买一价
        en_entrust_price = marketselfwidget->GetBuy1Price(contractName) + pFastInfo->OverPrice* overprice;
        msg = msg + QStringLiteral(" 买一价 ")+ QString::number(en_entrust_price);
        break;
    case 2://卖一价
        en_entrust_price = marketselfwidget->GetSell1Price(contractName) + pFastInfo->OverPrice* overprice;
        msg = msg + QStringLiteral(" 卖一价 ")+ QString::number(en_entrust_price);
        break;
    default://市场价  价格为0即可
        entrust_prop = "F1";
        msg = msg + QStringLiteral(" 市场价 ");
        break;
    }
    if(pFastInfo->bs == 0){//Buy
        bs = THOST_FTDC_D_Buy;
        msg = msg + QStringLiteral(" 买");
    }else if(pFastInfo->bs == 1){
        bs = THOST_FTDC_D_Sell;
        msg = msg + QStringLiteral(" 卖");
    }

    switch(pFastInfo->ActionType){
    case 0:{//发出报单(带确认)
        msg = msg +QString::number(l_entrust_amount) + QStringLiteral("手  ")+contractName+"?";
        int ret =  QMessageBox::question(this,QString("Question"),msg);
        if (ret == QMessageBox::Yes){
            //报单操作
            g_CTPInterface->OrderInsert(futuexchtype.toStdString().c_str(),contractName.toStdString().c_str(),bs,c_direction,c_hedge,
                                               l_entrust_amount,en_entrust_price,entrust_prop.toStdString().c_str());
        }
        break;}
    case 1://发出报单(不带确认)
        g_CTPInterface->OrderInsert(futuexchtype.toStdString().c_str(),contractName.toStdString().c_str(),bs,c_direction,c_hedge,
                                           l_entrust_amount,en_entrust_price,entrust_prop.toStdString().c_str());
        break;
    case 2://填单后光标不动
    case 3://填单后光标到合约代码
    case 4://填单后光标到买卖
    case 5://填单后光标到开平
    case 6://填单后光标到数量
    case 7://填单后光标到价格
    case 8://填单后光标到下单按钮
        controlwidget->SetOrderInfo(bs,c_direction,c_hedge,en_entrust_price,pFastInfo->ActionType);
        break;
    default:
        break;
    }
}

void MainWindow::closeEvent(QCloseEvent *event){
    QMessageBox::StandardButton button = QMessageBox::question(this, QStringLiteral("退出程序"),
                QString(QStringLiteral("是否确定退出程序?")),
                QMessageBox::Yes | QMessageBox::No);

    if (button == QMessageBox::No) {
        event->ignore();
    }else if (button == QMessageBox::Yes) {
        event->accept();
    }
}
void MainWindow::keyPressEvent(QKeyEvent *k){
    switch(k->key()){
    case Qt::Key_F2:{//F2 进入未成交单列表
        ui->dockWidget3->raise();
        return;
    }
    default:
        break;
    }
    m_pOrderSetterDlg->OrderDefaultAction(k);
}
void MainWindow::destroyWin(){
    m_MainPopDialog->accept();
}
void MainWindow::MainPopDlgShow(){
    m_MainPopDialog->show();
}
void MainWindow::OrderSetterDlgShow(){
    m_pOrderSetterDlg->show();
}
//退出服务器
void MainWindow::exit(){
    this->close();
}
void MainWindow::ShowStatusTip(QString msg){
    emit SigSetStatusTip(msg);
}

///交易服务器登录
void MainWindow::OnUserLogin(int iRetID, QString errInfo,QString username){
	if(iRetID == 0) {
		controlwidget->m_AccountCombox->insertItem(0,username);
		mainbalancewidget->m_accountCombox->insertItem(0,username);
		mainholdwidget->m_accountCombox->insertItem(0,username);
        mainbusinessqueryhiswidget->m_accountCombox->insertItem(0,username);

		///请求查询所有合约
		g_CTPInterface->ReqQryInstrument();

	} else {
		qDebug("Trader Login Failure");
	}

}
///请求查询投资者结算结果响应
void MainWindow::OnRspQrySettlementInfo(CThostFtdcSettlementInfoField *pSettlementInfo, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast){

    m_SettlementInfoDialog->OutputContent(QString::fromLocal8Bit(pSettlementInfo->Content));
    if (bIsLast == true)
    {
        emit SigShowSettlementInfoDialog();
    }
}
//交易者结算单确认
void MainWindow::SlotShowSettlementInfoDialog(){
    int iRet = this->m_SettlementInfoDialog->exec();
    if(1 == iRet){
        //点击确认按钮
        g_CTPInterface->ReqSettlementInfoConfirm();
    }else{
        //点击取消按钮
        ShowStatusTip(QStringLiteral("结算单未确认,不能进行交易!"));
    }
}
void MainWindow::OnRspQryInstrument(CThostFtdcInstrumentField *pInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast){
    //显示合约信息至 查询合约 Tab中
    if(pInstrument->ProductClass == THOST_FTDC_PC_Futures){
        this->maincontractwidget->AddRow(pInstrument);
        ((MainPopDialog*)m_MainPopDialog)->AddContractsInfo(pInstrument);
    }

    if (bIsLast){
        qDebug()<<QStringLiteral("查询获取全部合约信息成功");
        ShowStatusTip(QStringLiteral("查询获取全部合约信息成功"));
		Sleep(1000);
        //请求查询结算信息确认
        g_CTPInterface->ReqQrySettlementInfoConfirm();
    }
}
///投资者结算结果确认响应
void MainWindow::OnRspSettlementInfoConfirm(QString ConfirmDateTime){
    ShowStatusTip(QStringLiteral("投资者结算结果确认成功!确认时间:")+ConfirmDateTime);
	Sleep(1000);
	//查询资金
	g_CTPInterface->ReqQryTradingAccount();
}
///查询资金账户响应
void MainWindow::OnRspQryTradingAccount(CThostFtdcTradingAccountField *pTradingAccount, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast){
    if(NULL != pTradingAccount){
        mainbalancewidget->ShowTradingAccount(pTradingAccount);
    }
    if(bIsLast == true){
        qDebug()<<QStringLiteral("查询资金账户成功!");
        this->setStatusTip(QStringLiteral("查询资金账户成功!"));
        Sleep(1000);
        ///请求查询投资者持仓
        g_CTPInterface->ReqQryInvestorPosition();
    }
}
///查询持仓响应
void MainWindow::OnRspQryInvestorPosition(CThostFtdcInvestorPositionField *pInvestorPosition, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast){

    if(NULL != pInvestorPosition){
        int amountPerHand = maincontractwidget->GetAmountPerHand(QString(pInvestorPosition->InstrumentID));
        mainholdwidget->AddRow(pInvestorPosition,amountPerHand);
    }
    if(bIsLast == true){
        qDebug()<<QStringLiteral("查询持仓成功!");
        ShowStatusTip(QStringLiteral("查询持仓成功!"));
        //订阅保存的合约
        ((MainPopDialog*)m_MainPopDialog)->SubscribeContractsChoosed();
    }
}

void MainWindow::ReqQryInstrumentMarginRate(QString code){
    //查询保证金率
    Sleep(1000);
    if(!(maincontractwidget->m_MapBuyTouji.contains(code) && maincontractwidget->m_MapSellTouji.contains(code))){
        g_CTPInterface->ReqQryInstrumentMarginRate(code,THOST_FTDC_HF_Speculation);///投机
    }
    Sleep(1000);
    if(!(maincontractwidget->m_MapBuyTaoli.contains(code) && maincontractwidget->m_MapSellTaoli.contains(code))){
        g_CTPInterface->ReqQryInstrumentMarginRate(code,THOST_FTDC_HF_Arbitrage);///套利
    }
    Sleep(1000);
    if(!(maincontractwidget->m_MapBuyTaobao.contains(code) && maincontractwidget->m_MapSellTaobao.contains(code))){
        g_CTPInterface->ReqQryInstrumentMarginRate(code,THOST_FTDC_HF_Hedge);///套保
    }
    maincontractwidget->ShowInstrumentMarginRateInfo();
}
///请求查询合约保证金率响应
void MainWindow::OnRspQryInstrumentMarginRate(CThostFtdcInstrumentMarginRateField *pInstrumentMarginRate)
{
    switch (pInstrumentMarginRate->HedgeFlag) {
    case THOST_FTDC_HF_Speculation:
        maincontractwidget->m_MapBuyTouji.insert(QString(pInstrumentMarginRate->InstrumentID),pInstrumentMarginRate->LongMarginRatioByMoney);
        maincontractwidget->m_MapSellTouji.insert(QString(pInstrumentMarginRate->InstrumentID),pInstrumentMarginRate->ShortMarginRatioByMoney);
        break;
    case THOST_FTDC_HF_Arbitrage:
        maincontractwidget->m_MapBuyTaoli.insert(QString(pInstrumentMarginRate->InstrumentID),pInstrumentMarginRate->LongMarginRatioByMoney);
        maincontractwidget->m_MapSellTaoli.insert(QString(pInstrumentMarginRate->InstrumentID),pInstrumentMarginRate->ShortMarginRatioByMoney);
        break;
    case THOST_FTDC_HF_Hedge:
        maincontractwidget->m_MapBuyTaobao.insert(QString(pInstrumentMarginRate->InstrumentID),pInstrumentMarginRate->LongMarginRatioByMoney);
        maincontractwidget->m_MapSellTaobao.insert(QString(pInstrumentMarginRate->InstrumentID),pInstrumentMarginRate->ShortMarginRatioByMoney);
        break;
    default:
        break;
    }
}
/*
void MainWindow::ShowInstrumentMarginRateInfo(IF2UnPacker *lpUnPacker){

    if(mainholdwidget->GetInstrumentMarginRateFutucodeFlg()){
        this->maincontractwidget->ShowInstrumentMarginRateInfo(lpUnPacker);
    }else{
        this->maincontractwidget->ShowInstrumentMarginRateInfo(lpUnPacker);

        QString position_str= QString(lpUnPacker->GetStr("position_str"));
        if(position_str != ""){
            g_pCTradeByMarketData->QryInstrumentMarginRate("",position_str.toStdString().c_str());
        }else{
            this->maincontractwidget->ShowInstrumentMarginRateInfo();
        }
    }
}*/

///报单通知
void MainWindow::OnRtnOrder(CThostFtdcOrderField *pOrder){
    //交易所回报
    emit SigRaiseOrderDockWidget();//显示未成交单Tab
    this->maincombineentrustwidget->ShowBatchOrder(pOrder);//在未成交单Tab上显示报单信息
}
///成交通知
void MainWindow::OnRtnTrade(CThostFtdcTradeField *pTrade){
    //当收到成交回报时，更新用户的持仓信息
    mainholdwidget->QueryButtonClicked();
    /***
     * 这里不采用查询来更新用户的持仓 而采用实时计算来更新用户持仓
     * <暂未实现>
     ***/
    //mainholdwidget->UpdateHold(pTrade);

    emit SigRaiseOrderDockWidget();//显示未成交单Tab
    this->maincombineentrustwidget->UpdateBatchOrder(pTrade);//在未成交单Tab上 更新报单信息
}

///请求查询成交响应
void MainWindow::OnRspQryTrade(CThostFtdcTradeField *pTrade){
    this->mainbusinessqueryhiswidget->AddRow(pTrade);
}
///深度行情通知
void MainWindow::OnDepthMarketData(CThostFtdcDepthMarketDataField *pDepthMarketData){
    //显示行情
    marketselfwidget->ShowDepthMarketData(pDepthMarketData);
    //根据行情 更新持仓的损益
    mainholdwidget->UpdateByDepthMarketData(pDepthMarketData);
}

